// app.ts
App<IAppOption>({
  globalData: {
    userInfo: null,
    cartCount: 0,
    // API配置
    apiConfig: {
      baseUrl: 'http://localhost:8071/salon'
    }
  },
  
  onLaunch() {
    // 初始化本地存储
    this.initStorage()
    
    // 延迟检查登录状态，确保页面已经加载
    setTimeout(() => {
      this.checkLoginStatus()
    }, 100)
    
    // 微信登录（用于获取code）
    wx.login({
      success: res => {
        console.log('微信登录成功:', res.code)
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      },
    })
  },

  checkLoginStatus() {
    // 获取当前页面路径
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const currentRoute = currentPage ? currentPage.route : ''
    
    console.log('app checkLoginStatus currentRoute:', currentRoute)
    
    // 如果是登录页面，不跳转
    if (currentRoute && currentRoute.includes('login')) {
      console.log('当前是登录页面，不跳转')
      return
    }
    
    const isLoggedIn = wx.getStorageSync('isLoggedIn')
    const token = wx.getStorageSync('token')
    
    console.log('app checkLoginStatus isLoggedIn:', isLoggedIn, 'token:', token)
    
    if (!isLoggedIn || !token) {
      console.log('未登录，跳转到登录页面')
      wx.redirectTo({
        url: '/pages/login/login'
      })
    }
  },

  onShow() {
    // 更新购物车数量
    this.updateCartCount()
  },

  initStorage() {
    // 初始化用户数据
    if (!wx.getStorageSync('userInfo')) {
      wx.setStorageSync('userInfo', {
        avatar: '',
        nickName: '',
        phone: '',
        birthday: '',
        gender: 'secret'
      })
    }

    // 初始化预约记录
    if (!wx.getStorageSync('bookings')) {
      wx.setStorageSync('bookings', [])
    }

    // 初始化购买记录
    if (!wx.getStorageSync('purchaseHistory')) {
      wx.setStorageSync('purchaseHistory', [])
    }
  },

  updateCartCount() {
    const cart = wx.getStorageSync('cart') || []
    const cartCount = cart.reduce((sum: number, item: any) => sum + item.quantity, 0)
    this.globalData.cartCount = cartCount
    
    // 更新tabBar的购物车数量
    if (cartCount > 0) {
      wx.setTabBarBadge({
        index: 2,
        text: cartCount.toString()
      })
    } else {
      wx.removeTabBarBadge({
        index: 2
      })
    }
  }
})